<template>
  <el-card class="mr-20" shadow="never">
    <el-form :disabled="permissionDisabled()" ref="serialFormRef" :model="serialForm" :rules="serialRules" label-position="top" class="goodForm">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-form-item :label="$t('pageStr.ulBaudRateStr')" style="max-width: 900px">
            <el-select v-model="serialForm.baudrate" allow-create filterable class="w-full">
              <el-option v-for="item of baudRateArr" :value="item" :label="item"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item :label="$t('pageStr.ucDataBitsStr')" style="max-width: 500px">
            <el-select :disabled="enableDatabit" v-model="serialForm.dataBits" class="w-full">
              <el-option v-for="item of dataBitsArr" :value="item" :label="item"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item :label="$t('pageStr.eParityStr')" style="max-width: 500px">
            <el-select v-model="serialForm.parity" class="w-full">
              <el-option v-for="item of checkBit" :value="item.value" :label="item.label"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item :label="$t('pageStr.ucStopBitsStr')" style="max-width: 500px">
            <el-select v-model="serialForm.stop" class="w-full">
              <el-option v-for="item of stopBit" :value="item" :label="item"/>
            </el-select>
          </el-form-item>
        </el-col>
        <template v-if="netWorkForm.netMode != 'SSH mode'">
          <el-col :span="4">
            <el-form-item :label="$t('pageStr.serialframeStr')">
              <el-input-number :disabled="enableSerialFrame" v-model="serialForm.serial_frame" style="width: 100%;"
                               :min="0" :max="1460"/>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item :label="$t('pageStr.serialtimeStr')">
              <el-input-number v-model="serialForm.serial_time" style="width: 100%;" :min="100" :max="500"/>
            </el-form-item>
          </el-col>
        </template>
      </el-row>
    </el-form>
  </el-card>
  <el-card class="mt-10 mr-20" shadow="never">
    <el-form :disabled="permissionDisabled()" :model="netWorkForm" label-width="200px" label-position="left">
      <el-form-item :label="$t('pageStr.networkModeStr')" style="max-width:500px">
        <el-select v-model="netWorkForm.netMode" class="w-full" @change="netModeChange">
          <el-option v-for="(item,index) of netWorkMode" :key="index" :label="item.label" :value="item.value"/>
        </el-select>
      </el-form-item>
      <div v-show="netWorkForm.netMode != '_'">
        <div v-show="netWorkForm.netMode != 'ssh_server'">
          <el-form-item :label="$t('pageStr.transmitModeStr')" style="max-width: 500px">
            <el-select v-model="netWorkForm.enabled_modbus" class="w-full" @change="enabledModbusChange">
              <el-option label="Transparent" value="0"/>
              <el-option label="Modbus RTU" value="1"/>
            </el-select>
          </el-form-item>
          <div v-show="netWorkForm.enabled_modbus == 0">
            <el-form-item :label="$t('pageStr.simplexModeStr')"
                          style="max-width: 500px">
              <el-checkbox v-model="netWorkForm.enabled_single" true-label="1" false-label="0"/>
            </el-form-item>
            <el-form-item :label="$t('pageStr.encryptTypeStr')" style="max-width: 500px">
              <el-select v-model="netWorkForm.encrypt_type" class="w-full" @change="encryptTypeChange">
                <el-option v-for="(item,index) of encryptTypeArr" :key="index" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>

            <div v-show="netWorkForm.encrypt_type != '_'">
              <el-form-item :label="$t('pageStr.encryptModeStr')" style="max-width: 500px">
                <el-select v-model="netWorkForm.encrypt_mode" class="w-full">
                  <el-option value="ecb" label="ECB"></el-option>
                  <el-option value="cbc" label="CBC"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item :label="$t('pageStr.encryptPaddingStr')" style="max-width: 500px">
                <el-select v-model="netWorkForm.encrypt_padding" class="w-full">
                  <el-option value="pkcs7" label="PKCS7"></el-option>
                  <el-option value="zero" label="Zero"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item :label="$t('pageStr.encryptKeySizeStr')" style="max-width: 500px">
                <el-select :disabled="disableKeySize" v-model="netWorkForm.encrypt_key_size" class="w-full">
                  <el-option :disabled="true" value="8" label="64bit"/>
                  <el-option value="16" label="128bit"></el-option>
                  <el-option value="24" label="192bit"></el-option>
                  <el-option value="32" label="256bit"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item :label="$t('pageStr.encryptKeyStr')" style="max-width: 500px">
                <el-input v-model="netWorkForm.encrypt_key" clearable/>
              </el-form-item>
              <el-form-item v-if="netWorkForm.encrypt_mode == 'cbc'" :label="$t('pageStr.encryptIVStr')"
                            style="max-width: 500px">
                <el-input v-model="netWorkForm.encrypt_iv" clearable/>
              </el-form-item>
            </div>

            <el-form-item :label="$t('pageStr.serialHeartStr')" style="max-width: 500px">
              <el-checkbox v-model="netWorkForm.enabled_serialheart" true-label="1" false-label="0"/>
              <el-input v-model="netWorkForm.serial_packet" clearable style="width: 275px;margin-left: 10px" :maxlength="10"/>
            </el-form-item>
            <el-form-item :label="$t('pageStr.SerialHeartTimeStr')" style="max-width: 500px">
              <el-input-number v-model="netWorkForm.serial_hearttime" style="width: 100%;" :min="0" :max="1000"/>
            </el-form-item>
          </div>
        </div>

        <div v-show="netWorkForm.netMode=='tcp_server'">
          <el-form-item v-show="netWorkForm.enabled_modbus == 0" :label="$t('pageStr.ChannelCheckStr')"
                        style="max-width: 500px">
            <el-checkbox v-model="netWorkForm.enabled_check" true-label="1" false-label="0"/>
            <el-input v-model="netWorkForm.channel_passwd" clearable style="width: 275px;margin-left: 10px" :maxlength="10"/>
          </el-form-item>
          <el-form-item v-show="netWorkForm.enabled_modbus == 0" :label="$t('pageStr.ConnectInfoStr')"
                        style="max-width: 500px">
            <el-select v-model="netWorkForm.info_mode" class="w-full">
              <el-option label="Disable" value="0"/>
              <el-option label="IP Info" value="1"/>
              <el-option label="Device Info" value="2"/>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('pageStr.BindIpStr')"
                        style="max-width: 500px">
            <el-select v-model="netWorkForm.BindIp" class="w-full">
              <el-option label="Default" value="Disable"/>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('pageStr.localTcpPortStr')" style="max-width: 500px">
            <el-input-number v-model="netWorkForm.net_lport1" style="width: 100%;" :min="0" :max="65535"/>
          </el-form-item>
          <el-form-item v-show="netWorkForm.netMode != 'SSH mode'" :label="$t('pageStr.maxClientNumStr')"
                        style="max-width: 500px">
            <el-input-number v-model="netWorkForm.max_client" style="width: 100%;" :min="1" :max="8"/>
          </el-form-item>
          <el-form-item :label="$t('pageStr.keepAliveTimeStr')" style="max-width: 500px">
            <el-input-number v-model="netWorkForm.keepalive_time" style="width: 100%;" :min="1" :max="1000"/>
          </el-form-item>
          <el-form-item v-if="netWorkForm.enabled_modbus == 1" :label="$t('pageStr.pollingIntervalStr')"
                        style="max-width: 500px">
            <el-input-number v-model="netWorkForm.polling_interval" style="width: 100%;" :min="1" :max="1000"/>
          </el-form-item>
          <el-form-item v-if="netWorkForm.enabled_modbus == 0" :label="$t('pageStr.NodataTimeStr')"
                        style="max-width: 500px">
            <el-input-number v-model="netWorkForm.nodata_time" style="width: 100%;" :min="1" :max="1000"/>
          </el-form-item>
        </div>

        <div v-show="netWorkForm.netMode === 'tcp_client'">
          <el-form-item v-if="netWorkForm.enabled_modbus == 0" :label="$t('pageStr.ChannelCheckStr')"
                        style="max-width: 500px">
            <el-checkbox v-model="netWorkForm.enabled_check" true-label="1" false-label="0"></el-checkbox>
            <el-input v-model="netWorkForm.channel_passwd" clearable style="width: 275px;margin-left: 10px" :min="100"
                      :max="500"/>
          </el-form-item>
          <el-form-item v-if="netWorkForm.enabled_modbus == 0" :label="$t('pageStr.ConnectInfoStr')"
                        style="max-width: 500px">
            <el-select v-model="netWorkForm.info_mode" class="w-full">
              <el-option label="Disable" value="0"/>
              <el-option label="IP Info" value="1"/>
              <el-option label="Device Info" value="2"/>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('pageStr.keepAliveTimeStr')" style="max-width: 500px">
            <el-input-number v-model="netWorkForm.keepalive_time" style="width: 100%;" :min="1" :max="1000"/>
          </el-form-item>
          <el-form-item v-if="netWorkForm.enabled_modbus == 0" :label="$t('pageStr.NodataTimeStr')"
                        style="max-width: 500px">
            <el-input-number v-model="netWorkForm.nodata_time" style="width: 100%;" :min="1" :max="1000"/>
          </el-form-item>
          <el-form-item :label="$t('pageStr.ReconnectTimeStr')"
                        style="max-width: 500px">
            <el-input-number v-model="netWorkForm.reconnect_time" style="width: 100%;" :min="1" :max="1000"/>
          </el-form-item>
        </div>

        <div v-if="netWorkForm.netMode === 'udp_client'"></div>

        <div v-show="netWorkForm.netMode === 'udp_server'">
          <el-form-item :label="$t('pageStr.BindIpStr')"
                        style="max-width: 500px">
            <el-select v-model="netWorkForm.BindIp" class="w-full" clearable>
              <el-option label="Default" value="Disable"/>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('pageStr.localTcpPortStr')" style="max-width: 500px">
            <el-input-number v-model="netWorkForm.net_lport1" style="width: 100%;" :min="1" :max="65535"/>
          </el-form-item>
          <el-form-item v-if="netWorkForm.enabled_modbus == 0" :label="$t('pageStr.maxClientNumStr')"
                        style="max-width: 500px">
            <el-input-number v-model="netWorkForm.max_client" style="width: 100%;" :min="1" :max="8"/>
          </el-form-item>
          <el-form-item v-if="netWorkForm.enabled_modbus == 1" :label="$t('pageStr.pollingIntervalStr')"
                        style="max-width: 500px">
            <el-input-number v-model="netWorkForm.polling_interval" style="width: 100%;" :min="10" :max="1000"/>
          </el-form-item>
        </div>

        <div v-if="netWorkForm.netMode === 'ssh_server'">
          <el-form-item :label="$t('pageStr.localTcpPortStr')" style="max-width: 500px">
            <el-input-number v-model="netWorkForm.net_lport1" style="width: 100%;" :min="1" :max="65535"/>
          </el-form-item>
        </div>
        <el-form-item v-if="netWorkForm.enabled_modbus == 1 && netWorkForm.netMode != 'ssh_server'"
                      :label="$t('pageStr.rtuTimeoutStr')" style="max-width: 500px">
          <el-input-number v-model="netWorkForm.RTU_timeout" style="width: 100%;" :min="100" :max="9000"/>
        </el-form-item>
      </div>
    </el-form>
  </el-card>

  <el-card v-if="['tcp_client','udp_client'].includes(netWorkForm.netMode)" class="mt-10 mr-20" shadow="never">
    <el-form :disabled="permissionDisabled()" :model="targetIpForm">
      <el-table :data="targetIpForm.arr" :header-cell-style="tableHeadStyle">
        <el-table-column v-if="netWorkForm.enabled_modbus == 1" label="Slave Id" align="center" min-width="100">
          <template #default="{row}">
            <el-input v-model="row.macAddr" style="width: 95%" clearable/>
          </template>
        </el-table-column>
        <el-table-column :label="$t('pageStr.targetIpStr')" align="center" min-width="300">
          <template #default="{row}">
            <el-input v-model="row.macAddr" style="width: 95%" clearable/>
          </template>
        </el-table-column>
        <el-table-column :label="$t('pageStr.targetPortStr')" align="center" min-width="300">
          <template #default="{row}">
            <el-input v-model="row.remark" style="width: 95%" clearable/>
          </template>
        </el-table-column>
        <el-table-column :label="$t('pageStr.localTcpPortStr')" align="center" min-width="300">
          <template #default="{row}">
            <el-input v-model="row.remafrk" style="width: 95%" clearable/>
          </template>
        </el-table-column>
        <el-table-column v-if="!permissionDisabled()" width="80" align="center">
          <template #default="scope">
            <img v-if="targetIpForm.arr.length > 1" @click="handleRemoveRow(scope.$index,targetIpForm.arr)"
                 src="@/assets/icon/remove.png" class="removeIcon pointer">
            <img v-if="targetIpForm.arr.length < 4" @click="handleAddRow(scope.$index,targetIpForm.arr)"
                 src="@/assets/icon/add.png"
                 class="removeIcon pointer">
          </template>
        </el-table-column>
      </el-table>
    </el-form>
  </el-card>
  <el-button v-permissionShow style="margin-top: 20px;width: 110px;color: #fff" color="#C29B74" @click="handleSubmit">
    {{ $t('tabsStr.applyStr') }}
  </el-button>
</template>

<script setup>
import {reactive, ref, watch, onBeforeMount, defineProps} from 'vue'
import {reqGetSerialData, reqSetSerial} from '@/api/serial-server/serial-set'
import {ElMessage} from "element-plus";
import {useI18n} from 'vue-i18n'
import { permissionDisabled } from '@/utils'


const {t} = useI18n()
// table表头的样式
const tableHeadStyle = {
  'text-align': 'center',
  'background-color': '#F5EFE9',
  'max-width': '1000px'
}
const props = defineProps({
  serialId: {
    type: Number,
    default: 0,
    required: true
  }

})
const serialForm = ref({
  baudrate: '',
  dataBits: '',
  stop: '',
  parity: '',
  serial_frame: '',
  serial_time: '',
})
const netWorkForm = ref({
  netMode: 'tcp_server',
  enabled_modbus: '1',
  enabled_single: '0',
  encrypt_type: '_',
  encrypt_mode: '',
  encrypt_padding: '',
  encrypt_key_size: '',
  encrypt_key: '',
  encrypt_iv: '',
  enabled_serialheart: '',
  serial_packet: '',
  serial_hearttime: '',
  enabled_check: '',
  channel_passwd: '',
  info_mode: '',
  keepalive_time: '',
  nodata_time: '',
  reconnect_time: '',
  BindIp: '',
  net_lport1: '',
  max_client: '',
  polling_interval: '',
  RTU_timeout: '',
  net_if1: '',
  opmode: '2',
})
const targetIpForm = ref({
  arr: [{}]
})
const serialFormRef = ref()
const serialRules = reactive({})
const netWorkMode = [
  {label: 'Disabled', value: '_'},
  {label: 'TCP/Server', value: 'tcp_server'},
  {label: 'TCP/Client', value: 'tcp_client'},
  {label: 'UDP/Server', value: 'udp_server'},
  {label: 'UDP/Client', value: 'udp_client'},
  {label: 'SSH mode', value: 'ssh_server'}
]
const baudRateArr = [
  '50', '75', '110', '134', '150',
  '200', '300', '600', '1200', '2400',
  '4800', '9600', '19200', '38400',
  '57600', '115200', '230400', 'Customize']
const dataBitsArr = ['5', '6', '7', '8']
const checkBit = [
  {label: 'None', value: '0'},
  {label: 'Odd', value: '1'},
  {label: 'Even', value: '2'}]
const encryptTypeArr = [
  {label: 'Disabled', value: '_'},
  {label: 'DES', value: 'des'},
  {label: '3DES', value: '3des'},
  {label: 'AES', value: 'aes'}
]
const stopBit = ['1', '2']
const enableDatabit = ref(false)
const enableSerialFrame = ref(false)
onBeforeMount(() => {
  console.log('串口设置页面初始化')
  getData(props.serialId)
})

function handleSubmit() {
  const opMode = netWorkForm.value.netMode
  const oMArr = opMode.split('_');

  const submitForm = {...serialForm.value, ...netWorkForm.value}
  submitForm.net_pt = oMArr[0] || '';
  submitForm.net_md = oMArr[1] || '';
  submitForm.index = props.serialId
  submitForm.maxclientnum = netWorkForm.value.max_client
  console.log('提交表单', props.serialId, submitForm)
  reqSetSerial(submitForm).then(() => {
    ElMessage.success(t('successTip'))
  }).catch(() => {
    ElMessage.error(t('errorTip'))
  })
}

const disableKeySize = ref(false)

/**
 * 加密传输模式变化
 * @param val
 */
function encryptTypeChange(val) {
  console.log('加密模式变化', val)
  if (val == 'des') {
    disableKeySize.value = true
    netWorkForm.value.encrypt_key_size = '8'
  } else if (val == 'aes') {
    disableKeySize.value = false
    netWorkForm.value.encrypt_key_size = '24'
  } else if (val == '3des') {
    disableKeySize.value = true
    netWorkForm.value.encrypt_key_size = '24'
  }
}

/**
 * 网络模式选择变化事件
 * @param val 当前选择的网络模式
 */
function netModeChange(val) {
  const opMode = netWorkMode.findIndex((item) => {
    return item.value == val
  }) + 1
  netWorkForm.value.opmode = opMode.toString()
  console.log('单选下拉变化', val, opMode)
}

function handleRemoveRow(index, arr) {
  console.log('移除', index)
  arr.splice(index, 1)
}

function handleAddRow(index, arr) {
  if (arr && arr.length < 4) {
    arr.splice(index + 1, 0, {})
  }
}

/**
 * 传输模式选择更换
 */
function enabledModbusChange(val) {
  console.log('传输模式更换', val)
  if (val == '1') {
    enableDatabit.value = true
    enableSerialFrame.value = true
    serialForm.value.dataBits = '8'
    serialForm.value.serial_frame = '0'
  } else {
    enableDatabit.value = false
    enableSerialFrame.value = false
  }
}

/**
 * 数据回显
 * @param id 当前选择的串口号
 */
function getData(id) {
  reqGetSerialData(id).then(({serialData}) => {
    serialForm.value = {
      baudrate: serialData.srl_bt,
      dataBits: serialData.srl_dt,
      stop: serialData.srl_st,
      parity: serialData.srl_pt,
      serial_frame: serialData.serial_frame,
      serial_time: serialData.serial_time,
    }

    netWorkForm.value.netMode= (serialData.net_pt || '') + '_' + (serialData.net_md || '')
    netWorkForm.value.net_lport1= serialData.net_lport1
    netWorkForm.value.enabled_modbus= serialData.enabled_modbus
    netWorkForm.value.enabled_single= serialData.enabled_single
    netWorkForm.value.encrypt_type= serialData.encrypt_type || '_'
    netWorkForm.value.encrypt_mode= serialData.encrypt_mode || "ecb"
    netWorkForm.value.encrypt_padding= serialData.encrypt_padding || "pkcs7"
    netWorkForm.value.encrypt_key_size= serialData.encrypt_key_size || "16"
    netWorkForm.value.encrypt_key= serialData.encrypt_key
    netWorkForm.value.encrypt_iv= serialData.encrypt_iv
    netWorkForm.value.enabled_serialheart = serialData.enabled_serialheart
    netWorkForm.value.serial_packet = serialData.serial_packet
    netWorkForm.value.serial_hearttime = serialData.serial_hearttime
    netWorkForm.value.enabled_check = serialData.enabled_check
    netWorkForm.value.channel_passwd = serialData.channel_passwd
    netWorkForm.value.info_mode = serialData.info_mode
    netWorkForm.value.keepalive_time = serialData.keepalive_time
    netWorkForm.value.nodata_time = serialData.nodata_time
    netWorkForm.value.reconnect_time = serialData.reconnect_time
    netWorkForm.value.BindIp = serialData.BindIp
    netWorkForm.value.max_client = serialData.max_client
    netWorkForm.value.polling_interval = serialData.polling_interval
    netWorkForm.value.RTU_timeout = serialData.RTU_timeout
    netWorkForm.value.net_if1 = serialData.net_if1

    netModeChange(netWorkForm.value.netMode)
    encryptTypeChange(netWorkForm.value.encrypt_type)
    console.log(`请求到串口 ${id} 响应数据`, serialData, serialForm.value, netWorkForm.value)
    let arr = []
    // 遍历返回的对象所有字段
    Object.keys(serialData).forEach((key) => {
      if (key.includes('slave_id')) {
        console.log('slaveId',key, serialData[key])
      }
      if (key.includes('net_radd')) {
        console.log('目标ip',key, serialData[key])
      }
      if (key.includes('net_rport')) {
        console.log('目标端口',key, serialData[key])
      }
      if (key.includes('net_lport')) {
        console.log('本地端口',key, serialData[key])
      }
      if (key.includes('net_ifx')) {
        console.log('本地端口',key, serialData[key])
      }

    })

  })

  targetIpForm.value = {arr: [{}]}
}
</script>

<style scoped>
.removeIcon {
  width: 20px;
  height: 20px;
  margin-right: 10px;
}
</style>